﻿package fpc.utils;
import flash.display.Sprite;
import flash.events.Event;
import flash.utils.TypedDictionary;

/*
TODO

Попробовать заменить ENTER_FRAME на RENDER
*/

class FramePostponer 
{
	static var _sprite = new Sprite();
	
	static var _hasEnterFrame = false;
	
	static var _renderListeners = new TypedDictionary< Void->Dynamic, Bool >();
	
	public static function addRender(listener:Void->Dynamic)
	{
		_renderListeners.set(listener, true);
		if (!_hasEnterFrame)
		{
			_hasEnterFrame = true;
			_sprite.addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
	}
	
	static var _resizeListeners = new TypedDictionary< Void->Dynamic, Bool >();
	
	public static function addResize(listener:Void->Dynamic)
	{
		_resizeListeners.set(listener, true);
		if (!_hasEnterFrame)
		{
			_hasEnterFrame = true;
			_sprite.addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}
	}
	
	public static function remove(listener:Void->Dynamic)
	{
		_renderListeners.delete(listener);
		_resizeListeners.delete(listener);
	}
	
	static function onEnterFrame(e:Event)
	{
		_sprite.removeEventListener(Event.ENTER_FRAME, onEnterFrame);
		_hasEnterFrame = false;
		
		var listeners = _resizeListeners;
		_resizeListeners = new TypedDictionary();
		for (listener in listeners)
		{
			listener();
		}
		
		var listeners = _renderListeners;
		_renderListeners = new TypedDictionary();
		for (listener in listeners)
		{
			listener();
		}
	}
}